package org.base.oj.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
//设定将在含有这两个注解的类里生效
@ControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {
    /**
     * 自定义异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    public BaseResponse exceptionHandlerForBusiness(BusinessException e){
        log.info("出现异常！！！"+e.getMessage());
        return ResultUtils.error(ErrorCode.ERROR,e.getMessage());
    }

    /**
     * 认证异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(BadCredentialsException.class)
    public BaseResponse exceptionHandlerForSecurity(Exception e){
        e.printStackTrace();
        log.info("出现异常！！！"+e.getMessage());
        return ResultUtils.error(ErrorCode.ERROR,"认证失败:" + e.getMessage());
    }
    /**
     * 权限异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(AccessDeniedException.class)
    public BaseResponse exceptionHandlerForAcc(NullPointerException e){
        e.printStackTrace();
        log.info("出现异常！！！"+e.getMessage());
        return ResultUtils.error(ErrorCode.ERROR,"没有权限访问");
    }
    /**
     * 数据库异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(DataAccessException.class)
    public BaseResponse exceptionHandlerForData(DataAccessException e){
        log.info("出现异常！！！"+e.getMessage());
        if (e.getCause() instanceof SQLIntegrityConstraintViolationException){
           e.printStackTrace();
            return ResultUtils.error(ErrorCode.ERROR,"数据库字段冲突");
        }
        e.printStackTrace();
        return ResultUtils.error(ErrorCode.ERROR,"服务器内部错误");
    }
   @ResponseBody
   @ExceptionHandler(Exception.class)
    public BaseResponse exceptionHandler(Exception e){
        e.printStackTrace();
        log.info("出现异常！！！"+e.getMessage());
        return ResultUtils.error(ErrorCode.ERROR,"服务器内部错误");
    }

}